package org.example.Imp;

import exam.dao.Student_ExamDao;
import org.example.Student_ExamService;
import org.example.domain.Exam;
import org.example.domain.Question;
import org.example.domain.Student_Exam;
import org.example.pageParam.CommonData;
import org.example.vo.QuestionVO;
import org.example.vo.StudentExamAnswerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class Student_ExamServiceImp implements Student_ExamService {
    @Autowired
    private TemplateServiceImp templateServiceImp;
    @Autowired
    private Student_ExamDao student_examDao;
    @Override
    public int judgeGeneratePage(Long examId) {
        return student_examDao.selectGeneratePaperCount(examId);
    }

    @Override
    public void updateStudentPage_Path(Long examId, String page_path) {
        student_examDao.updateStudentPage_Path(examId,page_path);
    }

    @Override
    public List<Long> selectStudentIdsByExamId(Long examId) {
        return student_examDao.selectStudentIdsByExamId(examId);
    }

    @Override
    public void updateAllRelationStudentPage_path(Long examId, Long studentId, String page_path) {
        student_examDao.updateRelationStudentPage_path(examId,studentId,page_path);
    }

    @Override
    public void removeExamPage(Exam exam) {
        student_examDao.removeExamPage(exam.getId());

        //删除文件
        File file = new File(CommonData.COMMON_EXAM_PATH+exam.getName());
        File[] files = file.listFiles();
        for (File file1 : files){
            file1.delete();
        }
        file.delete();
    }

    @Override
    public int examGeneratePaperInfo(Long examId) {
        return student_examDao.selectExamPaperInfo(examId);
    }

    @Override
    public Student_Exam selectStudentExamByExamAndStudentId(Long examId, Long studentId) {
        return student_examDao.selectExamByExamIdAndStudentId(examId,studentId);
    }

    @Override
    public void updateStudentStatus(Long examId, Long studentId, String status) {
        student_examDao.updateStudentStatus(examId,studentId,status);
    }

    @Override
    public void updateStudentEnd_time(Long examId, Long studentId, Date date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        student_examDao.updateStudentEnd_time(examId,studentId,simpleDateFormat.format(date));
    }

    @Override
    public void updateStudentStart_time(Long examId, Long studentId) {
        student_examDao.updateStudentStart_time(examId,studentId);
    }

    @Override
    public void examAnswerSave(Map<String, String> map) {
        student_examDao.examAnswerSave(map);
    }

    @Override
    public StudentExamAnswerVO parseExamAnswer(Student_Exam student_exam) {
        List<Object> result = new ArrayList<>();
        List<String> answer_status = new ArrayList<>();
        {
            String answer1 = student_exam.getAnswer1();
            //如果前端没有单选题 那么数据库存储的就是null
            if (answer1!=null && !answer1.equals("")){
                String[] question1_answers  = answer1.split(CommonData.COMMON_SEPARATOR);
                for (int i = 0;i< question1_answers.length;i++){
                    String question1_answer = question1_answers[i];
                    if (!question1_answer.equals("no")){
                        answer_status.add("yes");
                    }else {
                        answer_status.add("no");
                    }
                    result.add(question1_answer);
                }
            }

        }
        {
            String answer2 = student_exam.getAnswer2();
            if (answer2!=null && !answer2.equals("")){
                String[] split = answer2.split(CommonData.COMMON_SEPARATOR);
                for (int i = 0;i<split.length;i++){
                    String question2_answer = split[i];
                    //首先这里有个问题 如果当前多选题没有存在答案存储的就是no
                    if (question2_answer.contains("no")){
                        //当前多选题没有选择答案
                        int tempAnswerLength = Integer.parseInt(question2_answer.split("-")[1]);
                        List<String> temp = new ArrayList<>();
                        for (int j = 0;j<tempAnswerLength;j++){
                            temp.add(" ");
                        }
                        answer_status.add("no");
                        result.add(temp);
                    }else {
                        //选择了答案 但是可能选择了一个 也可能选择多个 答案之间用-隔开的
                        String[] tempAnswer = question2_answer.split("-");
                        List<String> temp = new ArrayList<>();
                        for (int j = 0;j<tempAnswer.length;j++){
                            temp.add(tempAnswer[j]);
                        }
                        answer_status.add("yes");
                        result.add(temp);
                    }
                }
            }

        }
        {
            String answer3 = student_exam.getAnswer3();
            if (answer3!=null && !answer3.equals("")){
                String[] question3_answers = (answer3.split(CommonData.COMMON_SEPARATOR));
                for (int i = 0;i< question3_answers.length;i++){
                    String question_answer = question3_answers[i];
                    if (!question_answer.equals("no")){
                        answer_status.add("yes");
                    }else {
                        answer_status.add("no");
                    }
                    result.add(question_answer);
                }

            }

        }
        {
            String answer4 = student_exam.getAnswer4();
            if (answer4!=null && !answer4.equals("")){
                String[] question4_answers = answer4.split(CommonData.COMMON_SEPARATOR);
                for (int i = 0;i<question4_answers.length;i++){
                    List<String> question4_answer = Arrays.asList(question4_answers[i].split("-"));
                    if (question4_answer.contains("no")){
                        answer_status.add("no");
                    }else {
                        answer_status.add("yes");
                    }

                    result.add(question4_answer);
                }
            }

        }
        {
            String answer5 = student_exam.getAnswer5();
            if (answer5!=null && !answer5.equals("")){
               String[] question5_answers = answer5.split(CommonData.COMMON_SEPARATOR);
               for (int i =0;i< question5_answers.length;i++){
                   String question5_answer =question5_answers[i];
                   if (!question5_answer.equals("no")){
                       answer_status.add("yes");
                   }else {
                       answer_status.add("no");
                   }
                   result.add(question5_answer);
               }
            }
        }
        StudentExamAnswerVO studentExamAnswerVO = new StudentExamAnswerVO();
        studentExamAnswerVO.setAnswers(result);
        studentExamAnswerVO.setAnswerStatus(answer_status);
        return studentExamAnswerVO;
    }

    @Override
    public void finishExamToUpdateFinishStatus(Long examId) {
        student_examDao.finishExamToUpdateFinishStatus(examId);
    }

    @Override
    public void finishExamToUpdateMissStatus(Long examId) {
        student_examDao.finishExamToUpdateMissStatus(examId);
    }

    @Override
    public List<QuestionVO> generateExamPaper(String fileName) {
        File file = new File(fileName);
        List<QuestionVO> questionVOS = new ArrayList<>();
        try {
            FileReader fileReader = new FileReader(file);
            char[] chars = new char[1024];
            StringBuilder stringBuilder = new StringBuilder();
            int count ;
            while ((count = fileReader.read(chars))!=-1){
                stringBuilder.append(new String(chars,0,count));
            }//这是老师的代码  我自己写的io读取有问题 会读取到很多无关东西
            String page = stringBuilder.toString();
            String[] questions = page.split(CommonData.COMMON_QUESTION_SEPARATOR);
            for (int i = 0;i<questions.length;i++){
                //一个string就是一道题
                //第1题类型:单选题--/r/n
                //第1题分值:2--/r/n
                //第1题题干:以下那个是JAVA中的关键字5--/r/n
                //第1题选项:aaa}-|-{bbb}-|-{static}-|-{ddd}-|-{--/r/n
                //第1题答案:C}-|-{--/r/n
                String question = questions[i];
                Question tempQuestion = new Question();
                String[] currentQuestion = question.split(CommonData.COMMON_QUESTION_INNER_SEPARATOR);
                tempQuestion.setType(currentQuestion[0].split("\\:")[1]);
                tempQuestion.setYuliu1(currentQuestion[1].split("\\:")[1]);
                tempQuestion.setSubject(currentQuestion[2].split("\\:")[1]);
                tempQuestion.setOptions(currentQuestion[3].split("\\:")[1]);
                tempQuestion.setAnswer(currentQuestion[4].split("\\:")[1]);
//                questionVO.setType(currentQuestion[0].split("\\:")[1]);
//                questionVO.setScore(Integer.parseInt(currentQuestion[1].split("\\:")[1]));
//                questionVO.setSubject(currentQuestion[2].split("\\:")[1]);
//                questionVO.setOptions(currentQuestion[3].split("\\:")[1].split(CommonData.COMMON_SEPARATOR));
//                questionVO.setAnswers(currentQuestion[4].split("\\:")[1].split(CommonData.COMMON_SEPARATOR));
//                questionVOS.add(questionVO);
                QuestionVO questionVO = templateServiceImp.reverseVO(tempQuestion, i + 1);
                questionVO.setScore(Integer.parseInt(currentQuestion[1].split("\\:")[1]));
                questionVOS.add(questionVO);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return questionVOS;
    }

    @Override
    public void studentExamScoreSave(Long examId, Long studentId, int score) {
        student_examDao.studentExamScoreSave(examId,studentId,score);
    }

    @Override
    public void studentExamScoreStrSave(Long examId, Long studentId, String score_str) {
        student_examDao.studentExamScoreStrSave(examId,studentId,score_str);
    }

    @Override
    public List<Student_Exam> selectExamAllStudentByExamId(Long examId) {
        return student_examDao.selectExamAllStudentByExamId(examId);
    }

    @Override
    public void flushExamStudentScore(Student_Exam student_exam) {
        student_examDao.flushExamStudentScore(student_exam);
    }

    @Override
    public List<String> handleExamReviewInfo(List<QuestionVO> questionVOList, Student_Exam student_exam) {
        //student_exam中review4 和 review5 有两种情况 存在(没有批阅过) 不存在(没有批阅 为null)
        List<String> result = new ArrayList<>();
        String review4 = student_exam.getReview4();
        String review5 = student_exam.getReview5();
        if (review4 == null && review5 == null){
            for (int i = 0;i< questionVOList.size();i++){
                    result.add("");
            }
            return result;
        }
        List<String> reviewList = new ArrayList<>();
        Boolean exist4 = false;
        if (review4!= null){
            //表示填空题存在批阅
            exist4 = true;
            reviewList.addAll(Arrays.asList(review4.split(CommonData.COMMON_SEPARATOR)));
        }
        Boolean exist5 = false;
        if (review5 != null){
            //表示综合题存在批阅
            exist5 = true;
            reviewList.addAll(Arrays.asList(review5.split(CommonData.COMMON_SEPARATOR)));
        }
        int symbol = 0;//从批阅集合中获取批阅的索引
        for (int i = 0;i< questionVOList.size();i++){
            String type = questionVOList.get(i).getType();
            if (type.equals("填空题")){
                if (exist4){
                    //当前为填空题 并且存在批阅
                    result.add(reviewList.get(symbol++));
                }else {
                    result.add("");
                }
            }else if (type.equals("综合题")){
                if (exist5){
                    //当前为综合题 并且存在批阅
                    result.add(reviewList.get(symbol++));
                }else {
                    result.add("");
                }
            }else {
                result.add("");
            }
        }
        return result;
    }

    @Override
    public void reviewSave(Map<String, String> map) {
        student_examDao.reviewSave(map);
    }


}
